package com.rad.net.protocol.android.encoder;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;


/** 
 * 类说明： 此类对多个{@link InputStream}进行包装，同时输出。不支持{@link InputStream#reset()}
 * @author  xinhui.cheng
 * @date    2014-8-21
 * @version 1.0
 */
public class MultipleInputStream extends InputStream {

	private ArrayList<InputStream> mInputStreams;
	private int mCurrentIndex = 0;
	
	public MultipleInputStream(){}
	
	/**
	 * 构建一个包含输入流链表的对象
	 * @param inputStreams 输入流链表
	 */
	public MultipleInputStream(ArrayList<InputStream> inputStreams){
		mInputStreams = inputStreams;
	}
	
	
	@Override
	public int read() throws IOException {
		if(mInputStreams == null || mInputStreams.size()==0){
			return -1;
		}
		InputStream is = mInputStreams.get(mCurrentIndex);
		int len = -1;
		if((len = is.read())!= -1){
			return len;
		} else {
			if(mCurrentIndex < mInputStreams.size()-1){
				mCurrentIndex ++;
				return read();
			}
		}
		return -1;
	}
	
	
	@Override
	public int read(byte[] buffer) throws IOException {
		return read(buffer,0,buffer.length);
	}
	
	
	@Override
	public int read(byte[] buffer, int byteOffset, int byteCount)
			throws IOException {
		if(mInputStreams == null || mInputStreams.size()==0){
			return -1;
		}
		InputStream is = mInputStreams.get(mCurrentIndex);
		int len = -1;
		if((len = is.read(buffer,byteOffset,byteCount))!= -1){
			return len;
		} else {
			if(mCurrentIndex < mInputStreams.size()-1){
				mCurrentIndex ++;
				return read(buffer,byteOffset,byteCount);
			}
		}
		return -1;
	}
	
	/**
	 * 添加一个输入流对象
	 * @param is 输入流对象
	 */
	public void addInputStream(InputStream is){
		if(is == null){
			return ;
		}
		if(mInputStreams == null){
			mInputStreams = new ArrayList<InputStream>();
		}
		mInputStreams.add(is);
	}
	
	@Override
	public int available() throws IOException {
		if(mInputStreams == null){
			return 0;
		}
		int count = 0;
		for (int i = 0; i < mInputStreams.size() ; i++) {
			count+=mInputStreams.get(i).available();
		}
		return count;
	}

}
